import {
  confirm_saleContractSaleBill
} from "../components/api";
import store from '@/vuex/store'
import * as myApi from "@/components/api";
export default {

  install(Vue, options) {
    // // 获取商品列表
    // Vue.prototype.GoodsGoodsList = function(){
    //   this.request.post('qrcapi/Goods_goodsList',{
    //     sessionId: userList.sessionId,
    //     userId: userList.id,
    //       // goodsCategoryId //不传为全部商品
    //     //  saleStatus//-1,-2 强制下架   0：下架  1：上架
    //     //  pageNo //页码 [一页10条]
    //   }).then(res=>{
    //     console.log(res,'获取商品列表')
    //   })
    // }

    Vue.prototype.flexColumnWidth = function (str, tableData, flag = 'max', type) {
      // 自动计算表格宽度
      // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
      // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
      // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
      // type 为select 多给20px
      str = str + '';
      let columnContent = '';
      if (
        !tableData ||
        !tableData.length ||
        tableData.length === 0 ||
        tableData === undefined
      ) {
        return;
      }
      if (!str || !str.length || str.length === 0 || str === undefined) {
        return;
      }
      if (flag === 'equal') {
        // 获取该列中第一个不为空的数据(内容)
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i][str].length > 0) {
            // console.log('该列数据[0]:', tableData[0][str])
            columnContent = tableData[i][str];
            break;
          }
        }
      } else {
        // 获取该列中最长的数据(内容)
        let index = 0;
        for (let i = 0; i < tableData.length; i++) {
          if (!tableData[i][str]) {

          } else {
            const now_temp = tableData[i][str] + '';
            const max_temp = tableData[index][str] + '';
            if (now_temp.length > max_temp.length) {
              index = i;
            }
          }
        }
        columnContent = tableData[index][str];
      }
      if (str == 'companyName') {

        // console.log('该列数据[i]:', columnContent);
      }
      // 以下分配的单位长度可根据实际需求进行调整
      let flexWidth = 0;
      if (columnContent) {
        // if( str = 'refundUnit'){
        //    console.log('该列数据[i]:', columnContent);
        // }
        columnContent = String(columnContent) //避免数字型
        for (const char of columnContent) {
          if (

            (char >= 'a' && char <= 'z')
          ) {
            // 如果是小写英文字符，为字符分配8个单位宽度
            flexWidth += 8;
          } else if (char >= 'A' && char <= 'Z') {
            // 如果是大写英文字符，为字符分配10个单位宽度
            flexWidth += 10;
          } else if (char >= '\u4e00' && char <= '\u9fa5') {
            // 如果是中文字符，为字符分配15个单位宽度
            flexWidth += 20;
          } else {
            //   if( str = 'refundUnit'){
            //     console.log('该列数据[i]:', char);
            //  }
            // 其他种类字符，为字符分配8个单位宽度
            flexWidth += 9;
          }
        }
      }
      if (flexWidth < 80) {
        // 设置最小宽度
        flexWidth = 80;
        //大于最大小宽度且为输入框字符
        if (type == 'select') {
          flexWidth = flexWidth + 20
        }
      } else {
        //大于最大小宽度且为输入框字符
        if (type == 'select') {
          flexWidth = flexWidth + 50
        }
      }
      // if (flexWidth > 250) {
      //   // 设置最大宽度
      //   flexWidth = 250
      // }
      if (str == 'volume' || str == 'weight') {
        flexWidth = flexWidth + 60 //体积加上单位长度
        // console.log('volume宽度:', flexWidth);
      }

      return flexWidth;
    }

    Vue.prototype.guid = function () {
      return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    }

    //设置菜单待确认数量
    Vue.prototype.SET_MEANTOTAL = function () {
      console.log('设置菜单待确认数量')
      myApi.countNotConfirm_user().then((res) => {
        if (res.code == 200) {
          store.state.meanTotal = res.data
        }
      });
    }
    //把对象里的尾缀为Json的键值对  数组转换为JSON
    //type toJson 转换成JSON toString 转换成string
    Vue.prototype.Json_Array = function (jsonObject, type) {
      // console.log('jsonObject', jsonObject)
      for (var item in jsonObject) {
        if (jsonObject.hasOwnProperty(item)) {
          if (item.indexOf('Json') != -1) { //判断是否为JSON键值对

            if (type == 'toString') { //数组转字符串
              if (typeof (jsonObject[item]) == 'object') { //判断是否为数组 对象
                jsonObject[item] = JSON.stringify(jsonObject[item]);
              }
            } else { //字符串转数组
              if (typeof (jsonObject[item]) == 'string') {
                // console.log(jsonObject[item])
                jsonObject[item] = JSON.parse(jsonObject[item]);
              } else {
                jsonObject[item] = []
              }
            }
          }
        }
      }
      console.log(jsonObject)
      return jsonObject
    }
    Vue.prototype.jump = function (adress, query) {
      this.$router.push({
        path: adress,
        query: query
      });
    }
    //导出下载
    Vue.prototype.downLoad = function (response) {
      console.log(response)
      let filename = decodeURI(
        response.headers["content-disposition"].split(";")[1].split("=")[1]
      );
      let blob = new Blob([response.data]);
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.setAttribute("href", url);
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    //复制数据并取消关联性
    Vue.prototype.cloneObjectFn = function (obj) {
      // console.log(obj)
      if (obj) {

        return JSON.parse(JSON.stringify(obj))
      }
    }
    //表单验证
    Vue.prototype.watchLogin = function () {
      var reg = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){7,19}$/;

      var regPhone = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
      var phoneNumber = this.phoneNumber;
      var passWord = this.passWord;
      if (reg.test(passWord) && this.check && regPhone.test(phoneNumber)) {

        this.successButton = false;
      } else {
        this.successButton = true;

      }
    }
    //当前年月日
    Vue.prototype.nowDate = function () {
      var myDate = new Date();
      var nowDate = `${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()}`
      return nowDate
    }
    // 保存cookie
    Vue.prototype.setCookie = function (cName, value, expiredays) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiredays);
      document.cookie =
        cName +
        "=" +
        decodeURIComponent(value) +
        (expiredays == null ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
    }
    // 获取cookie
    Vue.prototype.getCookie = function (key) {
      if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(key + "=");
        if (start !== -1) {
          start = start + key.length + 1;
          var end = document.cookie.indexOf(";", start);
          if (end === -1) end = document.cookie.length;
          return unescape(document.cookie.substring(start, end));
        }
      }
      return "";
    }
    // 储存表单信息
    Vue.prototype.setUserInfo = function () {
      var that = this;
      // 判断用户是否勾选记住密码，如果勾选，向cookie中储存登录信息，
      // 如果没有勾选，储存的信息为空
      if (that.isRemember) {
        that.setCookie("account", that.phoneNumber);
        // base64加密密码
        that.setCookie("password", that.passWord);
        that.setCookie("remember", that.isRemember);
      } else {
        that.setCookie("account", "");
        that.setCookie("password", "");
      }
    }

  }
};
